package com.tjshop.android;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.StringRequest;
import com.tjshop.android.adapter.HorizontalListViewAdapter;
import com.tjshop.android.constants.UrlConfigs;
import com.tjshop.android.mcv.GlobeVars;
import com.tjshop.android.model.Comment;
import com.tjshop.android.model.GoodsFullDetails;
import com.tjshop.android.model.tj.json.CartModel;
import com.tjshop.android.util.ImageLoaderUtils;
import com.tjshop.android.view.HorizontalListView;
import com.tjshop.android.view.IndicatorView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class GoodsDetailActivity extends BaseActivity implements OnClickListener {

	private GoodsFullDetails goodsDetail = new GoodsFullDetails();
	
	private TextView goodsName,goodsDesc,mobilePrice,shopPrice,soldNum,commentNumber,goodsDetails,commentCount,commentName,commentDate,commentContent;
	private HorizontalListView relativeGoods;
	private ViewPager banner;
	private IndicatorView indicatorView;
	Button addToCart,buyNow;
	String gid = "";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_coupon_detail);
		setTheme(R.style.Theme_Sherlock);
		updateCommonReturnBar("产品详情");

		goodsName = (TextView) findViewById(R.id.goodsName);
		goodsDesc = (TextView) findViewById(R.id.goodsDesc);
		mobilePrice = (TextView) findViewById(R.id.mobilePrice);
		shopPrice = (TextView) findViewById(R.id.shopPrice);
		soldNum = (TextView) findViewById(R.id.soldNum);
		commentNumber = (TextView) findViewById(R.id.commentNumber);
		goodsDetails = (TextView) findViewById(R.id.twdetails);
		goodsDetails.setOnClickListener(this);
		commentCount = (TextView) findViewById(R.id.commentCount);
		commentCount.setOnClickListener(this);
		commentName = (TextView) findViewById(R.id.commentName);
		commentDate = (TextView) findViewById(R.id.commentDate);
		commentContent = (TextView) findViewById(R.id.commentContent);

		relativeGoods = (HorizontalListView) findViewById(R.id.relativeGoods);
		banner = (ViewPager) findViewById(R.id.banner);
		indicatorView = (IndicatorView) findViewById(R.id.indicatorView);
		
		addToCart = (Button) findViewById(R.id.addtocart);
		addToCart.setOnClickListener(this);
		buyNow = (Button) findViewById(R.id.buynow);
		buyNow.setOnClickListener(this);
		try {
			Bundle bundle = getIntent().getExtras();
			gid = bundle.getString("gId");

		} catch (Exception e) {
			e.printStackTrace();
		}
		getGoodsDetails();
	}
	
	private void initView() {
		initBannerSubject();
		goodsName.setText(goodsDetail.getName());
		goodsDesc.setText(goodsDetail.getGoods_brief());
		mobilePrice.setText("￥"+goodsDetail.getShop_price());
		shopPrice.setText("￥"+goodsDetail.getMarket_price());
		shopPrice .getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG );
		soldNum.setText("本月销售："+goodsDetail.getXl());
		
		
		goodsDetails.setOnClickListener(this);
		commentCount.setOnClickListener(this);
		
		if(goodsDetail.getPl().size()>0){
			int rank = 0;
			for(int i = 0;i<goodsDetail.getPl().size();i++){
				if(goodsDetail.getPl().get(i).getRank() == 5){
					rank++;
				}
			}
			commentNumber.setText(rank+"条好评(好评率"+100.0f*rank/goodsDetail.getPl().size()+"%)");
			Comment c = goodsDetail.getPl().get(goodsDetail.getPl().size()-1);
			commentCount.setText("累计评论"+goodsDetail.getPl().size()+"条");
			commentName.setText(c.getUser());
			commentDate.setText(c.getTime());
			commentContent.setText(c.getContent());
		}else{
			commentNumber.setVisibility(View.GONE);
			commentCount.setText("没有评论");
			commentName.setVisibility(View.GONE);
			commentDate.setVisibility(View.GONE);
			commentContent.setVisibility(View.GONE);
		}
		initRelativeGoods();
		
		
	}
	private void initRelativeGoods() {
		HorizontalListViewAdapter adapter = new HorizontalListViewAdapter(getApplicationContext(), goodsDetail.getGl());
		
		relativeGoods.setAdapter(adapter);
		
		relativeGoods.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent(getApplicationContext(),
						 GoodsDetailActivity.class);
						 intent.putExtra("gId",goodsDetail.getGl().get(arg2).getGoods_id());
						 startActivity(intent);
			}
		
		});
		
	}
	HashMap<Integer, ImageView> mBannerImageViews = new HashMap<Integer, ImageView>();
	List<String> mBannerImages;

	private void initBannerSubject() {
		// 显示的图片
		mBannerImages = new ArrayList<String>();
		for (int i = 0; i < goodsDetail.getXc().size(); i++) {
			mBannerImages.add(goodsDetail.getXc().get(i));

			ImageView view = new ImageView(this);
			view.setScaleType(ScaleType.CENTER);
			mBannerImageViews.put(i, view);

		}
		banner.setAdapter(adapter);
		banner.setOnPageChangeListener(MyOnPageChangeListener);

		indicatorView.setPointNum(mBannerImages.size());
		indicatorView.setSelectedIndex(0);
		indicatorView.postInvalidate();

	}

	OnPageChangeListener MyOnPageChangeListener = new OnPageChangeListener() {
		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			indicatorView.setSelectedIndex(arg0);
			indicatorView.postInvalidate();
		}

		@Override
		public void onPageSelected(int arg0) {
			indicatorView.setSelectedIndex(arg0);
			indicatorView.postInvalidate();
		}
	};
	PagerAdapter adapter = new PagerAdapter() {

		@Override
		public int getCount() {
			return mBannerImages.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
		}

		/**
		 * 载入图片进去，用当前的position 除以 图片数组长度取余数是关键
		 */
		@Override
		public Object instantiateItem(View container, final int position) {
			// System.out.println("装载"+position);
			ImageView v = mBannerImageViews.get(position);
			if (v.getTag() == null || !v.getTag().equals("hasParent")) {
				((ViewPager) container).addView(v, 0);
				v.setTag("hasParent");
				v.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
//						if (mBannerImageViews.get(position).equals(arg0)) {
//							Intent intent = new Intent(getActivity(),
//									BannerActivity.class);
//							Bundle b = new Bundle();
//							b.putString("title",
//									homeData.getBannerList().get(position)
//											.getAdName());
//							b.putString("url",
//									homeData.getBannerList().get(position)
//											.getAdlink());
//							intent.putExtras(b);
//							getActivity().startActivity(intent);
//						}
					}
				});
				ImageLoaderUtils.getInstance(getApplicationContext()).displayImage(
						mBannerImages.get(position), v);
			}
			return v;
		}
	};
	void getGoodsDetails (){
		mProgressDialog.show("获取商品详情", true, false);

		StringRequest stringRequest = new StringRequest(Method.GET,
				UrlConfigs.URL_GOODS_Details + "?gid=" + gid,
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
//						response = "{    'r': 0,    'cat_id': 3,    'name': '板蓝根颗粒',    'goods_name_style': '+',    'click_count': 208,    'goods_number': 20,    'market_price': 24,    'shop_price': 12,    'promote_price': 0,    'keywords': '',    'goods_brief': '板蓝根颗粒板蓝根颗粒板蓝根颗粒',    'xl': 100,    'xc': [        {            'fileurl': 'shop.511511.com/images/201501/goods_img/1665_P_1422329908686.jpg'        },        {            'fileurl': 'shop.511511.com/images/201501/goods_img/1665_P_1422329908106.jpg'        }    ],    'tw': {        'tm': 0,        'tmimgs': [],        'tjimgs': '/images/upload/Image/玉屏山板蓝根颗粒2.jpg'    },    'pl': [],    'gg': [],    'cs': [        {            'attrvalue': '袋',            'attrname': '计量单位'        },        {            'attrvalue': '10g*20袋',            'attrname': '商品规格'        },        {            'attrvalue': '颗粒剂',            'attrname': '剂型'        },        {            'attrvalue': '非处方药',            'attrname': '药品分类'        },        {            'attrvalue': '是',            'attrname': '检验合格'        }    ],    'gl': []}";
						JSONArray jsonU;
						try {
							JSONObject obj = new JSONObject(response);
							if (obj.getInt("r") == 0) {
								goodsDetail.parse(obj);
								Message message = new Message();
								message.what = 2;
								mHandler.sendMessage(message);
							} else {
								Message message = new Message();
								message.what = 1;
								mHandler.sendMessage(message);
							}

						} catch (JSONException e) {
							Message message = new Message();
							message.what = 1;
							mHandler.sendMessage(message);
							e.printStackTrace();
						}

					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						Message message = new Message();
						message.what = 1;
						mHandler.sendMessage(message);

					}

				});

		mQueue.add(stringRequest);
	}

	@Override
	public boolean handleMessage(Message message) {
		switch (message.what) {
		case 1:
			mProgressDialog.dismiss();
			break;
		case 2:
			mProgressDialog.dismiss();
			initView();
//			getComments();
			break;
		case 3:
			mProgressDialog.dismiss();
			initView();
			break;
		case 4:
			Toast.makeText(getApplicationContext(), "添加成功", Toast.LENGTH_SHORT).show();
			GlobeVars.CARTNUM++;
			break;
		case 5:
			Toast.makeText(getApplicationContext(), "添加失败", Toast.LENGTH_SHORT).show();
			break;
		default:
			break;
		}
		return false;
	}

	@Override
	public void onClick(View arg0) {
		Intent intent = new Intent();
		switch (arg0.getId()) {
		case R.id.addtocart:
			addToCart();
			break;
		case R.id.buynow:
			intent.setClass(getApplicationContext(), OrderActivity.class);
			intent.putExtra("url", goodsDetail.getTwDetail());
			CartModel c = new CartModel();
			c.setAttrname("");
			c.setAttrvalue("");
			c.setGid(gid);
			c.setGname(goodsDetail.getGoods_brief());
			c.setNum(1);
			c.setPrice(goodsDetail.getShop_price());
			c.setThumb(goodsDetail.getXc().get(0));
			List<CartModel> clList = new ArrayList<CartModel>();
			clList.add(c);
			Bundle b = new Bundle();
			b.putSerializable("goodslist", (Serializable) clList);
			intent.putExtras(b);
			startActivity(intent);
			break;
		case R.id.twdetails:
			intent.setClass(getApplicationContext(), TuwenDetailActivity.class);
			intent.putExtra("url", goodsDetail.getTwDetail());
			startActivity(intent);
			break;
		case R.id.commentCount:
			intent.setClass(getApplicationContext(), PinglunActivity.class);
			intent.putExtra("gId", goodsDetail.getCat_id());
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	private void addToCart() {
		if(!GlobeVars.isLogin){
			startActivity(new Intent(getApplicationContext(), LoginActivity.class));
			return;
		}
		StringRequest stringRequest = new StringRequest(Method.GET,
				UrlConfigs.URL_ADD_TO_CART + "?gid=" + gid+"&t="+GlobeVars.token+"&num="+1+"&good_attrid=1",
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						try {
							JSONObject obj = new JSONObject(response);
							if (obj.getInt("r") == 0) {
								Message message = new Message();
								message.what = 4;
								mHandler.sendMessage(message);
							} else {
								Message message = new Message();
								message.what = 5;
								mHandler.sendMessage(message);
							}

						} catch (JSONException e) {
							Message message = new Message();
							message.what = 5;
							mHandler.sendMessage(message);
							e.printStackTrace();
						}

					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						Message message = new Message();
						message.what = 5;
						mHandler.sendMessage(message);

					}

				});

		mQueue.add(stringRequest);
	}

	

	

}
